// $Id: request.c 52 2011-04-20 17:06:01Z cedric.shih@gmail.com $
/*
 * Copyright (C) 2010 Cedric Shih <cedric.shih@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdlib.h>
#include <string.h>

#include <nio.h>
#include <nio/buffer.h>

#include "request.h"

#include "niohttp/test.h"

#define BUFFER_SIZE 1024

static struct niohttp_request *req;
static struct niobuffer *buffer;
static struct niobuffer *content;

static void test_setup()
{
	req = niohttp_request_new();
	buffer = niobuffer_new(BUFFER_SIZE);
	content = niobuffer_new(BUFFER_SIZE);
}

static void test_teardown()
{
	niobuffer_free(content);
	niobuffer_free(buffer);
	niohttp_request_free(req);
}

static void test_init()
{
	TEST_ASSERT_NOT_NULL(req);
	TEST_ASSERT_NOT_NULL(buffer);
	TEST_ASSERT_NOT_NULL(content);
}

static void test_format()
{
	int rc;
	const char *expected;

	niohttp_request_clear_headers(req);
	niobuffer_clear(buffer);
	niobuffer_clear(content);

	rc = niohttp_request_set_protocol(req, "HTTP");
	TEST_ASSERT_EQUAL_INT(0, rc);

	rc = niohttp_request_set_version(req, "1.1");
	TEST_ASSERT_EQUAL_INT(0, rc);

	rc = niohttp_request_set_method(req, "GET");
	TEST_ASSERT_EQUAL_INT(0, rc);

	rc = niohttp_request_set_uri(req, "/");
	TEST_ASSERT_EQUAL_INT(0, rc);

	rc = niohttp_request_set_header(req, "Server", "niohttp-1.0");
	TEST_ASSERT_EQUAL_INT(0, rc);

	rc = niohttp_request_set_header(req, "Host", "127.0.0.1");
	TEST_ASSERT_EQUAL_INT(0, rc);

	rc = niohttp_request_format(req, buffer);
	TEST_ASSERT_EQUAL_INT(0, rc);

	expected = "GET / HTTP/1.1\r\n"
			"Host: 127.0.0.1\r\n"
			"Server: niohttp-1.0\r\n"
			"\r\n";

	TEST_ASSERT_EQUAL_INT(0, strncmp(expected,
			(char *)niobuffer_array(buffer), strlen(expected)));
}

TestRef niohttp_request_test()
{
	EMB_UNIT_TESTFIXTURES(fixtures) {
		new_TestFixture("niohttp_request_test_init", test_init),
		new_TestFixture("niohttp_request_test_format", test_format),
	};
	EMB_UNIT_TESTCALLER(test_case, "niohttp_request_test", test_setup, test_teardown, fixtures);
	return (TestRef)&test_case;
}
